<template>
	<view class="page-container">

		<!-- 顶部导航栏 -->
		<u-navbar title="数据" placeholder :autoBack="false" :border="false" :bgColor="'#fff'">
			<template v-slot:left>
				<!-- 左边插槽为空，相当于隐藏返回图标 -->
			</template>
		</u-navbar>

		<!-- 顶部标签栏 -->
		<view class="tab-container">
			<u-tabs :list="tabList" :current="currentTab" lineColor="#d9822b" @change="onTabChange"
				:labelStyle="{ fontWeight: '600', fontSize: '42rpx', color: '#333333' }"
				:itemStyle="{ padding: '8rpx 24rpx'}" />
		</view>


		<!-- 页面主体内容 -->
		<scroll-view class="content" scroll-y :scroll-with-animation="true" @scrolltolower="loadMore"
			lower-threshold="50" :style="{height: contentHeight}">
			<view v-if="loading" class="loading-text">加载中...</view>
			<view v-else-if="list.length === 0" class="empty-text">暂无抽题记录,返回上上签长按知识库/笔记进行抽题～</view>
			<view v-else>
				<view v-for="item in list" :key="item.id" class="card" @click="onCardClick(item)">
					<view class="card-title">📌 {{ item.noteName }}</view>
					<view class="progress-bar-container">
						<view class="progress-bar-bg">
							<view class="progress-bar-fill" :style="{ width: item.drawProcess }"></view>
						</view>
						<view class="progress-text">{{ item.drawProcess }}</view>
					</view>
				</view>
				<!-- 加载更多提示 -->
				<view v-if="loadingMore" class="loading-text">加载更多中...</view>
				<view v-else-if="noMore" class="empty-text">没有更多了</view>
				<view v-else class="loading-text">下滑查看更多～</view>
			</view>
		</scroll-view>

		<custom-tab-bar :currentIndex="3"></custom-tab-bar>
	</view>
</template>

<script>
	import dataApi from "@/api/data.js";
	import loginRequest from "@/api/login.js";

	export default {
		data() {
			return {
				list: [],
				tabList: [{
						name: "抽题记录进度"
					},
					// {
					// 	name: "最新资讯"
					// },
					// {
					// 	name: "标签3"
					// }
				],

				loading: true, // 首次加载loading
				loadingMore: false, // 加载更多loading
				noMore: false, // 是否已无更多数据
				currentPage: 1, // 当前页码
				pageSize: 10,
				currentTab: 0,
				contentHeight: '0px', // 动态计算高度
			};
		},

		async onLoad() {
			  this.calcContentHeight();
			await this.getDrawDetail()
		},


		async onShow() {
			  this.calcContentHeight();
			await this.getDrawDetail()
		},


		methods: {
			
			calcContentHeight() {
			  const systemInfo = uni.getSystemInfoSync();
			  const windowHeight = systemInfo.windowHeight;
			  // 转换为rpx单位（1px=2rpx）
			  const pxToRpx = 2;
			  // 估算需要减去的高度（导航栏+标签栏+底部安全区）
			  const navBarHeight = 90; // 导航栏大约90rpx
			  const tabBarHeight = 120; // 底部tabbar高度
			  const tabContainerHeight = 80; // 标签栏高度
			  const totalReduce = (navBarHeight + tabBarHeight + tabContainerHeight) * pxToRpx;
			  
			  this.contentHeight = `${windowHeight * pxToRpx - totalReduce}rpx`;
			},

			// 点击抽题记录卡片跳转抽题页面
			onCardClick(item) {
				if (item.drawProcess === '100%') {
					uni.showToast({
						title: '该笔记已完成抽题',
						icon: 'none'
					});
					return;
				}
				// 获取笔记类型
				const noteType = item.noteType

				// 跳转到抽题页面，传参
				uni.navigateTo({
					url: `./drawTopicPage?noteId=${item.noteId}&noteName=${encodeURIComponent(item.noteName)}&noteType=${noteType}`
				});

			},

			// 切换顶层tab页
			onTabChange(index) {
				this.currentTab = index;
				// 这里可以根据 currentTab 请求不同数据
				this.getDrawDetail();
			},

			// 获取抽题数据
			async getDrawDetail(page = 1) {
				if (page === 1) {
					this.loading = true;
					this.noMore = false;
				} else {
					this.loadingMore = true;
				}

				try {
					const userId = uni.getStorageSync("userId");
					if (!userId) await this.autoLogin();
					const finalUserId = uni.getStorageSync("userId");
					const bindType = uni.getStorageSync("bindType");
					if (!finalUserId) {
						uni.showToast({
							title: "登录失败，请重试",
							icon: "none"
						});
						return;
					}

					const params = {
						currentPage: page,
						pageSize: this.pageSize,
						userId: finalUserId,
						userType: bindType,
					};

					const res = await dataApi.getHistoryDrawDataDetail(params);
					if (res?.data?.code === 200) {
						const newList = res.data.data.content || [];
						if (page === 1) {
							this.list = newList;
						} else {
							this.list = [...this.list, ...newList];
						}
						if (newList.length < this.pageSize) {
							this.noMore = true;
						}
						this.currentPage = page;
					} else {
						uni.showToast({
							title: "数据加载失败",
							icon: "none"
						});
					}
				} catch (err) {
					console.error("接口调用异常:", err || "未知错误");
					uni.showToast({
						title: "网络异常",
						icon: "none"
					});
				} finally {
					this.loading = false;
					this.loadingMore = false;
				}
			},

			loadMore() {
				if (this.loading || this.loadingMore || this.noMore) {
				      return;
				    }
				    this.getDrawDetail(this.currentPage + 1);
			},


			// 自动重新登录
			async autoLogin() {
				try {
					const loginRes = await uni.login({
						provider: 'weixin',
						onlyAuthorize: true
					});
					const jsCode = loginRes.code;

					const res = await loginRequest.loginApi(jsCode);
					if (res.data.code === 200) {
						uni.setStorageSync('token', res.data.data?.token);
						uni.setStorageSync('userId', res.data.data?.userId);
						uni.setStorageSync('bindCode', res.data.data?.bindCode);
						uni.setStorageSync('bindType', res.data.data?.bindType);
					} else {
						throw new Error(res.data.message || '登录失效，请重新登录');
					}
				} catch (error) {
					uni.showToast({
						title: '登录异常，请重试',
						icon: 'none'
					});
				}
			},

		}
	};
</script>

<style lang="scss" scoped>
	.page-container {
		display: flex;
		flex-direction: column;
		background-color: #f8f8f8;
		min-height: 100vh;
		box-sizing: border-box;
		height: 100vh;
		/* 这里必须设置全屏高度 */
		padding-bottom: 120rpx; // 预留底部 tabBar 空间
	}

	/* 顶部标签栏 */
	.tab-container {
		padding: 20rpx 32rpx 0;
		align-items: center;
		justify-content: center;
		background-color: #ffffff;
		box-shadow: 0 4rpx 10rpx rgba(0, 0, 0, 0.04);
		border-radius: 0 0 24rpx 24rpx;
		z-index: 10;
	}

	/* 内容区 */
	.content {
		flex: 1;
		flex-direction: column;
		padding: 30rpx;

		.empty-text,
		.loading-text {
			position: relative; // 或直接删掉
			width: 100%;
			text-align: center;
			font-size: 30rpx;
			color: #999;
			padding: 60rpx 0;
		}

		.card {
			background-color: #ffffff;
			border-radius: 20rpx;
			padding: 32rpx 28rpx;
			margin-bottom: 28rpx;
			box-shadow: 0 6rpx 16rpx rgba(0, 0, 0, 0.05);

			.card-title {
				font-weight: 700;
				font-size: 34rpx;
				color: #222222;
				margin-bottom: 20rpx;
				white-space: nowrap;
				overflow: hidden;
				text-overflow: ellipsis;
			}

			.progress-bar-container {
				display: flex;
				align-items: center;
			}

			.progress-bar-bg {
				flex: 1;
				height: 16rpx;
				background-color: #f0f0f0;
				border-radius: 8rpx;
				overflow: hidden;
				margin-right: 16rpx;
			}

			.progress-bar-fill {
				height: 100%;
				background-color: #d9822b;
				border-radius: 8rpx 0 0 8rpx;
				transition: width 0.3s ease;
			}

			.progress-text {
				font-size: 28rpx;
				color: #d9822b;
				font-weight: 600;
				min-width: 50rpx;
				text-align: right;
			}
		}
	}


	/* 抽题项卡片 */
	.item {
		background-color: #ffffff;
		border-radius: 20rpx;
		padding: 32rpx;
		margin-bottom: 28rpx;
		box-shadow: 0 6rpx 16rpx rgba(0, 0, 0, 0.05);
		transition: all 0.2s;

		view {
			font-size: 30rpx;
			color: #333333;
			margin-bottom: 12rpx;

			&:first-child {
				font-weight: bold;
				font-size: 32rpx;
				color: #222;
			}
		}

		&:active {
			transform: scale(0.98);
			box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
		}
	}

	/* 加载/空状态 */
	.loading-text,
	.empty-text {
		text-align: center;
		font-size: 30rpx;
		color: #999;
		padding: 80rpx 0;
	}

	/* tab 样式建议设置为居中加强调 */
	::v-deep .u-tabs__wrapper {
		justify-content: center !important;
	}

	::v-deep .u-tabs__item {
		font-weight: 600;
		font-size: 32rpx !important;
		padding: 12rpx 28rpx !important;
		border-radius: 32rpx;
		transition: background-color 0.3s;
	}

	::v-deep .u-tabs__item--active {
		background-color: #fff2e5;
		color: #d9822b !important;
	}
</style>